from tkinter import *
from tkinter import messagebox, ttk
import socket
import re
import threading
from web import start_server, stop

sys.stderr = open('error.log', 'a')
# sys.stdout=open('sendwx.log','a')

cf = {'startWx': 0, 'mode': 1, 'ip': '', 'port': 8899, 'url': 'http://localhost', 'interval': 120}


def write_cf(cf):
    wcf = open('zsend.conf', 'w')
    wcf.write(str(cf))
    wcf.close()


try:
    rcf = open('zsend.conf', 'r')
    constr = rcf.read().strip()
    rcf.close()
    if constr:
        cf = eval(constr)
except:
    write_cf(cf)

hostname = socket.gethostname() if not cf['ip'] else cf['ip']
root = Tk()
root.title('自动发微信')
root.geometry('+600+300')
root.resizable(False, False)
# root.update()

app = Frame(root)
th = None

Label(app, text="启动微信：").grid(row=0, column=0)
start_wx = ttk.Combobox(app, width=25)
start_wx['values'] = ('是', '否')
start_wx.current(cf['startWx'])
start_wx.grid(row=0, column=1, pady=5)


def mode_change(e):
    if mode.get() == '客户端':
        ipLabel.config(text="请求URL(http)：")
        portLabel.config(text="请求间隔(s)：")
        ipVar.set(cf['url'])
        portVar.set(cf['interval'])
        cf['mode'] = 1
    else:
        ipLabel.config(text="ip地址：")
        portLabel.config(text="监听端口：")
        ipVar.set(hostname)
        portVar.set(cf['port'])
        cf['mode'] = 0


Label(app, text="模式：").grid(row=1, column=0, pady=5)
mode = ttk.Combobox(app, width=25)
mode['values'] = ('服务端', '客户端')
mode.bind("<<ComboboxSelected>>", mode_change)
mode.current(cf['mode'])
mode.grid(row=1, column=1, pady=5)

ipLabel = Label(app, text="ip地址：")
ipLabel.grid(row=2, column=0, pady=5)
ipVar = StringVar()
ipVar.set(hostname)
e1 = Entry(app, bd=3, textvariable=ipVar, width=27)
e1.grid(row=2, column=1, pady=5)

portLabel = Label(app, text="监听端口：")
portLabel.grid(row=3, column=0)
portVar = StringVar()
portVar.set(cf['port'])
e2 = Entry(app, bd=3, textvariable=portVar, width=27)
e2.grid(row=3, column=1, pady=5)


def btn_start():
    host = e1.get().strip()
    port = int(e2.get().strip())
    try:
        if mode.get() == '客户端':
            if not re.match(r'http\w?://', host):
                raise Exception('error')
            cf['url'] = host
            cf['interval'] = port
        else:
            cf['ip'] = host
            cf['port'] = port

        global th
        th = threading.Thread(target=start_server, args=(host, port, start_wx.get(),))
        th.setDaemon(True)  # 守护线程
        th.start()
        b1['state'] = 'disabled'

        cf['startWx'] = start_wx.current()
        write_cf(cf)
    except Exception as error:
        print(str(error))
        messagebox.showerror('错误', '请输入正确的启动参数，如客户端url格式http(s)://host:port/xxx')


def btn_stop():
    stop()
    b1['state'] = 'normal'


b1 = Button(app, text='启动', command=btn_start, width=10)
b1.grid(row=4, column=0, sticky=W, padx=10, pady=5)
b2 = Button(app, text='停止', command=btn_stop, width=10)
b2.grid(row=4, column=1, sticky=E, padx=10, pady=5)

app.pack(padx=15, pady=15)
mode_change(None)
mainloop()
